package com.token.iot.bratterycharging.gateway;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PreDestroy;

import com.outstanding.framework.core.PendingException;

import io.netty.channel.ChannelHandlerContext;

/**
 * 通道管理器
 * 
 * @author chenzhixuan
 *
 */
public class ChannelHandlerContextManager {

	private static final Map<String, ChannelHandlerContext> clients = new ConcurrentHashMap<>();

	
	
	
	@PreDestroy
	public void destory() {
		clients.clear();
	}

	/**
	 * 
	 * @param imei
	 * @return 当上下文为空时给出异常
	 * @throws PendingException
	 */
	static public ChannelHandlerContext getChannelHandlerContextByImei(String imei) throws PendingException {
		ChannelHandlerContext ctx = clients.get(imei);
		if(ctx == null) {
			throw new PendingException(ResCode.ContextISNULL);
		}
		return ctx;
	}

	
	static public ChannelHandlerContext putIfAbsent(String imei, ChannelHandlerContext ctx) {
		return clients.put(imei, ctx);
	}

	
	static public void remove(String imei) {
		clients.remove(imei);
	}

	
	static public void put(String imei, ChannelHandlerContext ctx) {
		clients.put(imei, ctx);
	}

	
	static public boolean isEmpty() {
		return clients.isEmpty();
	}
}
